use std::env;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use toml::from_str;
use crate::error::{ProxyError, ProxyResult};

enum ProxyMode {
    /// 单机代理
    SingleServer,
    /// 主备代理
    MasterBackup,
    /// 多活代理
    MultiActive,
}

pub struct ConfigOption {
    port: u16,
    mode: ProxyMode,
    log_save_date: u32,
}

impl ConfigOption {
    pub fn parse_file(config_path: Option<String>) -> ProxyResult<ConfigOption> {
        let config_file_path = match config_path {
            Some(x) => PathBuf::from(x.trim()),
            _ => {
                // 获取程序目录
                let current_file = env::current_exe().unwrap();
                current_file.parent().unwrap().join("config\\redisoxy.toml")
            }
        };

        println!("Using config file: {}", config_file_path.display());

        let mut config_file = match File::open(&config_file_path) {
            Ok(f) => f,
            Err(e) => return Err(ProxyError::ServerError(e.to_string()))
        };

        let mut contents = String::new();
        if let Err(e) = config_file.read_to_string(&mut contents) {
            return Err(ProxyError::ServerError(e.to_string()));
        }

        let config: toml::Value = match from_str(&contents) {
            Ok(v) => v,
            Err(e) => return Err(ProxyError::ServerError(e.to_string()))
        };

        println!("{:?}", config);

        Ok(ConfigOption{
            port: 6379,
            mode: ProxyMode::MultiActive,
            log_save_date: 7,
        })
    }
}